package com.seeyon.apps.reimburseplugin.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.reimburseplugin.util.HttpUtils;
import com.seeyon.apps.reimburseplugin.util.YRUtil;
import com.seeyon.apps.reimburseplugin.util.YrHttpUtils;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;

public class FyGxWorkflowEvent extends AbstractWorkflowEvent {
	
	private static final Log logger=LogFactory.getLog(FyGxWorkflowEvent.class);
	
	@Override
	public String getId() {
		return "fygxworkflowevent";
	}

	@Override
	public String getLabel() {
		return "合同推送";
	}

	@Override
	public ApplicationCategoryEnum getAppName() {
		return ApplicationCategoryEnum.form;
	}


	private OrgManager orgManager;
	
	private ColManager colManager;
	
	private TemplateManager templateManager;
	
	private EnumManager enumManagerNew;
	
	private AttachmentManager attachmentManager;

	private AttachmentDAO attachmentDAO = (AttachmentDAO) AppContext.getBean("attachmentDAO");
	
	public OrgManager getOrgManager() {
		return orgManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public ColManager getColManager() {
		return colManager;
	}

	public void setColManager(ColManager colManager) {
		this.colManager = colManager;
	}

	public TemplateManager getTemplateManager() {
		return templateManager;
	}

	public void setTemplateManager(TemplateManager templateManager) {
		this.templateManager = templateManager;
	}
	

	public EnumManager getEnumManagerNew() {
		return enumManagerNew;
	}

	public void setEnumManagerNew(EnumManager enumManagerNew) {
		this.enumManagerNew = enumManagerNew;
	}
	

	public AttachmentManager getAttachmentManager() {
		return attachmentManager;
	}

	public void setAttachmentManager(AttachmentManager attachmentManager) {
		this.attachmentManager = attachmentManager;
	}

	// 处理前事件
	@Override
	public WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {
		
		WorkflowEventResult eventResult = new WorkflowEventResult();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		try {
			Long summaryId = data.getSummaryId();
			ColSummary colSummary = colManager.getSummaryById(summaryId);
			paramMap.put("subject", colSummary.getSubject());
			paramMap.put("createTime", colSummary.getCreateDate());
			V3xOrgMember startMember = orgManager.getMemberById(colSummary.getStartMemberId());
			paramMap.put("sendUserCode",startMember.getCode() );
			paramMap.put("sendUserName", startMember.getName());
			CtpTemplate ctpTemplate = templateManager.getCtpTemplate(colSummary.getTempleteId());
			paramMap.put("templateId", colSummary.getTempleteId()+"");
			paramMap.put("templateSubject", ctpTemplate.getSubject());
			paramMap.put("templateNumber", ctpTemplate.getTempleteNumber());
			paramMap.put("summaryId", summaryId+"");
			FormDataMasterBean formDataBean = (FormDataMasterBean) data.getBusinessData().get("formDataBean");
			FormBean formBean = (FormBean) data.getBusinessData().get("formBean");
			Map<String,Object> allDataMap = new HashMap<String,Object>();
			Map<String,Object> rowData = formDataBean.getRowData();//主表数据
			FormTableBean formmainTableBean = formDataBean.getFormTable();
			this.detailDataAllMap(formBean, rowData);
			allDataMap.put(formmainTableBean.getTableName(), rowData);
			Map<String, List<FormDataSubBean>> map = formDataBean.getSubTables();
			if(!map.isEmpty()) {
				for(Map.Entry<String, List<FormDataSubBean>> obj:map.entrySet()) {
					List<FormDataSubBean> subDatas  = obj.getValue();
					List<Map<String,Object>>  list = new ArrayList<Map<String,Object>>();
					String subtable = "";
					for(FormDataSubBean subData:subDatas) {
						FormTableBean formTableBean = subData.getFormTable();
						subtable = formTableBean.getTableName();
						Map<String, Object> subMap =subData.getRowData();
						this.detailDataAllMap(formBean, subMap);
						list.add(subMap);
						
					}
					allDataMap.put(subtable, list);
				}
			}
//			Map<String,Object> allDataMap = formDataBean.getAllDataMap();
//			allDataMap = this.detailDataAllMap(formBean, allDataMap);
			
			paramMap.put("formData", allDataMap);
			
			
			List<Long> references = new ArrayList<Long>();
			references.add(Long.valueOf(summaryId));
			List<Attachment> attachments = attachmentDAO.getByReference(references);
				StringBuilder sbr=new StringBuilder();
				StringBuilder filenames=new StringBuilder();
				if (attachments!=null&&attachments.size()>0) {
					for(int i=0;i<attachments.size();i++) {
						Attachment attachment=attachments.get(i);
						String attName=attachment.getFilename();
						String att=attachment.getFileUrl()+"";
						if (i==0) {
							filenames.append(attName);
							sbr.append(att);
						}else {
							filenames.append("|"+attName);
							sbr.append("|"+att);
						}
					}
					paramMap.put("attachmentNum", attachments.size());
					paramMap.put("attachmentName", filenames.toString());
					paramMap.put("attachmentId", sbr.toString());
				}else {
					paramMap.put("attachmentNum",0);
					paramMap.put("attachmentId", "");
					paramMap.put("attachmentName", "");
					
				}
			logger.info("推送json："+JSONUtil.toJSONString(paramMap));
			String url=AppContext.getSystemProperty("reimburseplugin.interfaceUrl");
			String newUrl=url+"?service=fy_economic_contract&urid=oa&pwd=oa";
			String result = new YrHttpUtils().httpPost(newUrl, JSONUtil.toJSONString(paramMap));
			logger.info("推送返回信息："+result);
			if(Strings.isNotEmpty(result)) {
				Map<String,Object> mapres = JSONUtil.parseJSONString(result, Map.class); 
				if(YRUtil.getString(mapres.get("code")).equals("0")) {
				}else {
					eventResult.setAlertMessage(mapres.get("message").toString());
				}
			}else {
				eventResult.setAlertMessage("推送返回信息为空！");
			}
			
//			
//			Map<String,Object> masterMap = formDataBean.getRowData();//主表数据
			
		} catch (Exception e) {
			eventResult.setAlertMessage("合同推送异常：" + e.getMessage());
			logger.error("合同推送异常：",e);
		}

		return eventResult;

	}
	
	  public Map<String,Object> detailDataAllMap(FormBean fromBean4,Map<String, Object> allDataMap){
			try {
				for( com.seeyon.cap4.form.bean.FormTableBean table : fromBean4.getTableList()){
						if(table.isMainTable()){
							for (FormFieldBean fieldBean : table.getFieldsByName()) {
								if (allDataMap.get(fieldBean.getName()) != null) {
									if(fieldBean.getInputType().toLowerCase().equals("radio") || fieldBean.getInputType().toLowerCase().equals("select")) {
										CtpEnumItem ctpEnumItem =enumManagerNew.getEnumItem(Long.valueOf(allDataMap.get(fieldBean.getName()).toString()));
										allDataMap.put(fieldBean.getName(),ctpEnumItem.getShowvalue());
										allDataMap.put(fieldBean.getName()+"_code",ctpEnumItem.getEnumItemCode());
										allDataMap.put(fieldBean.getName()+"_value",ctpEnumItem.getValue());
									}else if(fieldBean.getInputType().toLowerCase().equals("member")) {
										V3xOrgMember orgMember =orgManager.getMemberById(Long.valueOf(allDataMap.get(fieldBean.getName()).toString()));
											allDataMap.put(fieldBean.getName(),orgMember.getCode());
											allDataMap.put(fieldBean.getName()+"_name",orgMember.getName());
									}else if(fieldBean.getInputType().toLowerCase().equals("department")){
										V3xOrgDepartment orgDepartment = orgManager.getDepartmentById(Long.valueOf(allDataMap.get(fieldBean.getName()).toString()));
										allDataMap.put(fieldBean.getName(),orgDepartment.getCode());
										allDataMap.put(fieldBean.getName()+"_name",orgDepartment.getName());
									}else if(fieldBean.getInputType().toLowerCase().equals("attachment")){
										String subReference = allDataMap.get(fieldBean.getName()).toString();
										if(Strings.isNotEmpty(subReference)) {
											List<Long> subreferences = new ArrayList<Long>();
											 subreferences.add(Long.valueOf(subReference));
											 List<Attachment> attachments = attachmentManager.getBySubReference(subreferences);
//											List<Long> fileUrls =  attachmentManager.getBySubReference(Long.valueOf(subReference));
											if(attachments != null && attachments.size() > 0) {
												String fileUrl = "";
												for (int i = 0; i < attachments.size(); i++) {
													if(i == (attachments.size() -1) ) {
														fileUrl =fileUrl + attachments.get(i).getFileUrl().toString()+"|"+attachments.get(i).getFilename();
													}else {
														fileUrl =fileUrl + attachments.get(i).getFileUrl().toString()+"|"+attachments.get(i).getFilename()+",";
													}
													
												}
												allDataMap.put(fieldBean.getName(),fileUrl);
											}
										}
										
										
									}else {
										allDataMap.put(fieldBean.getName(),allDataMap.get(fieldBean.getName()));
									}
								}
							}
						}
				}
			}catch (Exception e) {
				logger.info("detailDataAllMap error:", e);
			}
			return allDataMap;
	   }

}
